package src

import (
	"fmt"
	"time"

	"gitee.com/haifengat/goctp"
	ctp "gitee.com/haifengat/goctp/lnx"
	"github.com/sirupsen/logrus"
)

var q = ctp.NewQuote()

func startQuote() {
	logrus.Info("connect to quote ...")

	var chConnected = make(chan bool)
	q.RegOnFrontConnected(func() {
		logrus.Infoln("quote connected")
		chConnected <- true
		q.ReqLogin(investorID, password, brokerID)
	})
	q.RegOnFrontDisConnected(func(reason int) {
		logrus.Info("quote disconected ", reason)
		if reason != 0 {
			releaseQuote()
		}
	})
	q.RegOnRspUserLogin(onMdLogin)

	q.ReqConnect(quoteFront)
	go func() {
		// 连接超时设置
		select {
		case <-chConnected:
		case <-time.After(10 * time.Second):
			fmt.Println("连接超时")
			releaseQuote()
		}
	}()
}

func releaseQuote() {
	q.Release()
	q = ctp.NewQuote()
}
func onMdLogin(login *goctp.RspUserLoginField, info *goctp.RspInfoField) {
	logrus.Infoln("quote login:", info)
	// 订阅行情
	var i int
	var insts = make([]string, 0)
	t.Instruments.Range(func(k, v interface{}) bool {
		if len(v.(*goctp.InstrumentField).ProductID) == 0 { // 过滤 非正常合约
			return true
		}
		insts = append(insts, k.(string))
		if len(insts) > 200 { // 一次订阅 200个合约
			q.ReqSubscript(insts)
			insts = make([]string, 0)
		}
		i++
		return true
	})
	q.ReqSubscript(insts)
	logrus.Infof("subscript instrument count: %d", i)
}
